var express = require('express');
// var mongoose = require('mongoose')
var router = express.Router();
require ('../util/util'); 
var Users = require('../models/users')

/* GET users listing. */
router.get('/', function(req, res, next) {
  res.send('respond with a resource');
});
// 登陆
router.post('/login', function(req,res,next){
  // 获取用户信息
  let userInfo = {
    userName: req.body.userName,
    userPwd: req.body.userPwd
  }
  Users.findOne(userInfo,function(err, doc){
    if (err) {
      res.json({
        msg: err.message,
        status: '1'
      })
    }else{
      if(doc){
        res.cookie('userId',doc.userId,{
          path:'/',
          maxAge:1000 * 60 * 60
        })
        res.cookie('userName',doc.userName,{
          path:'/',
          maxAge:1000 * 60 * 60
        })
        res.json({
          msg:'',
          status: '0',
          result:{
            userName: doc.userName
          }
        })
      }else{
        res.json({
          msg:'',
          status: '1',
        })
      }
    }
   })
 })
//  登出
 router.post('/loginout',function(req,res,next){
   res.clearCookie('userId',{path:'/'});
   res.clearCookie('userName',{path:'/'});
   res.json({
     msg:'',
     status:'0',
     result: ''
   })
 })

// 检测是否登陆 
router.post('/checkLogin', function(req,res,next){
  if(req.cookies.userId){
    res.json({
      msg: '',
      status: '0',
      result: req.cookies.userName
    })
  }else{
    res.json({
      msg: '用户未登录',
      status : '1',
      result : ''
    })
  }
})

// 获取购物车列表
router.get('/cartList', function (req,res,next) {  
  let userId = req.cookies.userId;
  Users.findOne({userId: userId }, function (err, doc) {  
    if(err){
      return res.json({
        status:'1',
        msg : err.message,
        result:''
      })
    }
    if(doc){
      res.json({
        status:'0',
        msg:'',
        result: doc.cartList
      })
    }
  })
})
//  删除购物车
router.post('/cartDel', function (req, res, next) {  
  let userId = req.cookies.userId,productId = req.body.productId;
  Users.update({'userId':userId},{$pull:{
    cartList: {
      productId: productId
    }
  }},function (err,doc) { 
    if(err){
      return res.json({
        status: '1',
        err: err.message,
        result: ''
      })
    }
    console.log(doc)
    res.json({
      msg :'',
      status: '0',
      result: 'suc'
    })
  })
})
// 修改商品信息功能
router.post('/cartEdit',function (req, res, enxt) {  
  let userId = req.cookies.userId,
      productId = req.body.productId,
      productNum = req.body.productNum,
      checked = req.body.checked ;
  Users.update({userId:userId,"cartList.productId": productId},{
    "cartList.$.productNum":productNum,
    "cartList.$.checked":checked,
  }, function(err,doc){
    if(err){
      return res.json({
              msg: err.message,
              status: 1
            })
    }
    res.json({
      msg:'',
      status:0,
      result: 'suc'
    })
  })
})
// 全选
router.post('/checkedAll', function (req, res, next) {  
  let userId = req.cookies.userId,
      checkedAll = req.body.checkedAll? '1' : '-1';
  Users.findOne({userId:userId},function (err,doc) {  
    if(err){
      res.json({
        msg: err.message,
        status: "1"
      })
    }else{
      if(doc){
        doc.cartList.forEach((item)=>{
          item.checked = checkedAll
        })
        doc.save(function (err,data) {  
          if(err){
            res.json({
              msg: err.message,
              status: "1"
            })
          }else{
            res.json({
              msg: '',
              status: "0",
              result: 'suc'
            })
          }
        })
      }
    }
  })
})
// 查询地址列表
router.get('/address',function(req,res,next){
  let userId = req.cookies.userId;
  Users.findOne({userId:userId},function(err, doc){
    if(err){
      res.json({
        msg: err.message,
        status: "1"
      })
    }else{
      res.json({
        msg:'',
        status: "0",
        result:doc.addressList
      })
    }
  })
})
// 设置默认地址
router.post('/setDefault',function (req,res,next) {  
  let userId = req.cookies.userId,
      addressId = req.body.addressId;
  Users.findOne({userId:userId},function(err, doc){
    if(err){
      res.json({
        msg: err.message,
        status: "1"
      })
    }else{
      if(doc){
        let addressList = doc.addressList;
        addressList.forEach(item => {
          if(addressId == item.addressId){
            item.isDefault = true;
          }else{
            item.isDefault = false;
          }
        });
        doc.save(function (err,doc) {  
          if(err){
            res.json({
              msg: err.message,
              status: "1"
            })
          }else{
            res.json({
              msg: "",
              status: "0",
              result: ''
            })
          }
        })
      }
    }
  })
})

// 删除地址
router.post('/delAddress', function (req, res ,next) {  
  let userId = req.cookies.userId, addressId = req.body.addressId
  Users.update({'userId':userId},{
    $pull:{
      addressList: {
        addressId: addressId
      }
  }},function (err,doc) { 
    if(err){
      return res.json({
        status: '1',
        err: err.message,
        result: ''
      })
    }
    res.json({
      msg :'',
      status: '0',
      result: 'suc'
    })
  })
})
// payment 付款
router.post('/payment', function (req, res, next) {  
   let userId = req.cookies.userId,
       addressId = req.body.addressId,
       ordertotal = req.body.ordertotal;
    //  1.获取用户信息
    Users.findOne({userId:userId}, function (err,doc) {  
      if(err){
        res.json({
          status:'1',
          result: '',
          msg : err.message
        })
      }else{
        let address = {},
            goodsList = []
        // 将地址保存
        doc.addressList.forEach((item) =>{
          if(item.addressId == addressId){
            return address = item
          }
        })
        goodsList = doc.cartList.filter( item => {
          return item.checked == 1
        })
        // 生成订单号
        let platform = '622';
        let r1 = Math.floor(Math.random()*10);
        let r2 = Math.floor(Math.random()*10);

        // 与订单拼接
        let sysDate = new Date().Format('yyyyMMddhhmmss');
        // 生成订单时间
        let createDate = new Date().Format('yyyy-MM-dd hh:mm:ss');
        // 生成订单号码
        let orderId = platform+r1+sysDate+r2;
        
        // 生成订单详情
        let order = {
          orderId : orderId,
          orderTotal : ordertotal,
          addressInfo : address,
          goodsList: goodsList,
          orderStatus: '1',
          createDate : createDate
        }
        // 新增用户订单列表
        doc.orderList.push(order);
        // 保存
        doc.save(function (err,doc) {  
          if(err){
            res.json({
              status:'1',
              result: '',
              msg : err.message
            })
          }else{
            // 返回订单id 和订单总价
            res.json({
              status: '0',
              msg: '',
              result: {
                orderId: order.orderId,
                ordertotal : order.orderTotal
              }
            })
          }
        })
      }
    })
})

// 获取订单详情
router.get('/orderDetail',function (req, res, next) {  
  let userId = req.cookies.userId, orderId = req.query.orderId;
  Users.findOne({ userId: userId }, function (err, doc) {  
    if(err){
      res.json({
        status:'1',
        result: '',
        msg : err.message
      })
    }else{
      let orderList = doc.orderList
      // 看有无订单 没有订单返回 120001状态码
      if(orderList.length > 0){
        let orderTotal = 0
        orderList.forEach(function (item) {  
          if(item.orderId == orderId ){
            orderTotal = item.orderTotal
          }
        })
        // 更加严谨的 判断金额是否大于0  不大于0 证明订单异常
        if(orderTotal > 0){
          res.json({
            status: '0',
            msg : '',
            result: {
              orderTotal:orderTotal
            },
          })
        }else{
          res.json({
            status:'120002',
            result: '',
            msg : '订单异常'
          })
        }
      }else{
        res.json({
          status:'120001',
          result: '',
          msg : '无此订单'
        })
      }
    }
  })
})

// 购物车商品总数
router.get('/getCartCount', function (req, res, next) {  
  let userId = req.cookies.userId;

  Users.findOne({ userId: userId}, function (err, doc) {  
    if(err){
      return res.json({
        msg: err.message,
        status: 1
      })
    }
    let cartCount = 0;
    let cartList = doc.cartList;
    cartList.forEach((item) => {
      cartCount+= parseInt(item.productNum)
    })
    res.json({
      status: '0',
      msg: '',
      result:{
        cartCount: cartCount
      }
    })
  })
})
module.exports = router;
